<?php
/*
 * @description: Контроллер для работы с лекциями
 * @copyright Copyright (c) 2012-2017 Marin V. , Tykva A. , Kozel R. , Sokolov D.
 * @version 1.0
 * @link http://lecturebox.ru
*/

class LecturesController extends Model_Controller
{
    public function init()
    {
        /**
         * В parent::init() выполняется создание объекта Zend_Auth - $this->auth
         * и определение id текущего пользователя - $this->user_id
         */
        parent::init();
    }

    public function indexAction()
    {

    }
    
    /**
     * Загрузка лекции
     */
    public function addAction() 
    {
        $session = new Zend_Session_Namespace('lectureBox.l10n');
            if ($session->locale) {
                    if($session->locale == 'ru_RU'){
                        $this->view->title = 'Добавить новую лекцию';
                        $this->view->headTitle($this->view->title, 'PREPEND');
                        $this->view->headMeta()->appendName('description',
                                'Добавить лекции. Страница загрузки лекций.');
                    } else {
                        $this->view->title = 'Add new lecture';
                        $this->view->headTitle($this->view->title, 'PREPEND');
                        $this->view->headMeta()->appendName('description',
                                'Add lecture. Upload lecture page.');
                    }
            }
         $cid = $this->getParam('cid');
         
         
         $course = new Model_Course($cid);
         $work = new Model_Lecture();
        
         $auth = Zend_Auth::getInstance();
        $identity = $auth->getIdentity();
        $role = Bootstrap::getRole($identity->role);
        
        $_row = $course->getCoursesById($cid);
        foreach ($_row as $item){
            $this->iddd = $item['course_id'];
            $this->iudd = $item['user_id'];
        }

        if(!isset($this->iddd)){
            $this->getHelper('Redirector')->gotoSimpleAndExit('nfound','Error', false,array(null));
        }
        if($this->user_id != $this->iudd){
            if($role != 'admin'){
                $this->getHelper('Redirector')->gotoSimpleAndExit('access','Error', false,array(null)); 
            }
        }
        
        if($this->getRequest()->getParam('id')){
          
            
            if($this->getParam('status')==200){
                
                if ($session->locale) {
                    if($session->locale == 'ru_RU'){
                        $this->view->result = 'Лекция успешно добавлена ';
                    } else {
                        $this->view->result = 'Lecture successfully added ';
                    }
                }
                
                //echo $this->getParam('status')."\n";
                //echo $this->getParam('id')."\n";
                //echo $this->getParam('cid')."\n";
                //echo $this->getParam('unq')."\n";
                
                $work->getVideoByWriteCode($this->getParam('unq'));
                $work->writecode = 'done';
                $work->youtube_id = $this->getParam('id');
                $work->user_id = $this->user_id;
                $work->date = date("Y-m-d H:i:s");
                $work->save();
                $this->view->lecid = $work->lecture_id;
                $this->view->script = 2;
                
                $sub = new Model_Subscribe(); 
                $_row = $sub->getSubscribes($cid);
            
                $course = new Model_Course();            
                $_rowC = $course->getCoursesById($cid);
                foreach ($_rowC as $item){
                     $cname = $item['name'];
                } 

                foreach ($_row as $item){
                     $work->sendNoticeEmail($item['email'], $cid, $cname);
                } 
            }
            if($this->getParam('status')!=200){
                if ($session->locale) {
                    if($session->locale == 'ru_RU'){
                        $this->view->result =  'Что-то пошло не так, повторите попытку позже.';
                    } else {
                        $this->view->result =  'Something is going wrong, try later';
                    }
                }
              $work->getVideoByWriteCode($this->getParam('unq'));
              $work->delete();
              $this->view->script = 3;
            }
       
        }
        else{
            $authenticationURL = 'https://www.google.com/accounts/ClientLogin'; 
            try{
                $httpClient = Zend_Gdata_ClientLogin::getHttpClient(
                $this->getFrontController()->getParam('bootstrap')->getOption('yusername'),                                                                                                                                                                               
                $this->getFrontController()->getParam('bootstrap')->getOption('ypassword'),                                                                          
                $this->getFrontController()->getParam('bootstrap')->getOption('yservice'),                                                                                                                          
                null,                                                                                                                                 
                $this->getFrontController()->getParam('bootstrap')->getOption('yname'),                                                                              
                null,                                                                                                                             
                null,                                                                                                                           
                $authenticationURL);

                $developerKey = $this->getFrontController()->getParam('bootstrap')->getOption('ycode');                                                                                              
                $httpClient->setHeaders('X-GData-Key', "key=$developerKey"); //ключ разработчика

                $yt = new Zend_Gdata_YouTube($httpClient);
                $myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
                $counter = count($work->getCourseLectures($cid))+1;
                $pieces = explode(" ", $course->name);
                
                $videoName= $pieces[0];
                if(!empty($pieces[1])){
                    $videoName .=' '.$pieces[1];
                    if(strlen($videoName)>=30){
                        $videoName = $pieces[0].' '.substr($pieces[1],0,20);
                        if(strlen($videoName)>=30){
                            $videoName = substr($pieces[0],0,30);
                        }
                    }
                    //if(!empty($pieces[2])){
                       // $videoName.=' '.$pieces[2];
                    //}
                }
                $nameString = 'LectureBox.ru '.$videoName.' Лекция '.$counter;

                $myVideoEntry->setVideoTitle($nameString); // Заголовок видео                                       
                $myVideoEntry->setVideoDescription('Вы можете просмотреть эти 
                    классные лекции на LectureBox.ru'); //Описание видео                                    
                // Категория должна соотретствовать разрешенным категориям на youtube!                                    
                $myVideoEntry->setVideoCategory('Tech');                                                                 
                $myVideoEntry->SetVideoTags('Study, science'); //Ключевые слова, через запятую  
                $tokenHandlerUrl = 'http://gdata.youtube.com/action/GetUploadToken';                                      
                $tokenArray = $yt->getFormUploadToken($myVideoEntry, $tokenHandlerUrl);

                $tokenValue = $tokenArray['token'];//token который нужно будет отправить вместе с видео           
                $postUrl = $tokenArray['url']; // урл на который отправим форму с видео                           

                //код для поиска видео

                $unqid = uniqid();

                $nextUrl = $this->getFrontController()->getParam('bootstrap')
                        ->getOption('urlsite').'/lectures/add/cid/'
                        .$cid.'/'.'unq/'.$unqid; //Урл на который нужно попасть после загрузки видео 
                //$nextUrl = 'http://sigma-project/lectures/add ';
                if ($session->locale) {
                    if($session->locale == 'ru_RU'){
                        $form = '<form name="youtube_form" action="'. $postUrl .'?nexturl='. $nextUrl .
                       '" method="post" enctype="multipart/form-data" id="youtube_form">'.
                       'Имя Лекции'.
                       '<p><input type="Text" name="name" id="lectureName" onkeypress="check();" /></p>'.
                       '<input type="hidden" name="writecode" id="lectureWritecode" value="'.$unqid.'" />'.
                       '<input type="hidden" name="cid" id="lecturecid" value="'.$cid.'" />'. 
                       'Описание'.
                       '<p><textarea type="text" name="Description" id="lectureDescription" onChange="check();"></textarea></p>'.
                       '<p> <span id = "aboutAdd">Для загрузки файла введите Имя и Описание </span> <img id="RunLoadingRun" width="32" height ="32" src = "/www/images/YTLoad.gif" hidden></p>'.
                       '<p id = "aboutFiles">Допустимые форматы файлов: WMV, FLV, AVI, 
                           MPEG4, 3GPP, MOV, MPEGPS, Файлы WebM</p>'.
                        '<p id = "aboutTime">Загружайте HD-видео продолжительностью до 15 мин</p>'.
                       '
                                       <span>Выберите лекцию:</span>
                                       <input name="file" type="file" id="fileAdd" disabled/>'.
                       '<input name="token" type="hidden" value="'. $tokenValue .'"/>'.
                       '<p><input name = "goForest" value="Добавить лекцию" type="submit" 
                           id="SendData" style="margin-top: 18px;"
                           class="btn btn-inverse" disabled /></p>'.
                       '</form>';
                    } else {
                        $form = '<form name="youtube_form" action="'. $postUrl .'?nexturl='. $nextUrl .
                       '" method="post" enctype="multipart/form-data" id="youtube_form">'.
                       'Lecture name'.
                       '<p><input type="Text" name="name" id="lectureName" onkeypress="check();" /></p>'.
                       '<input type="hidden" name="writecode" id="lectureWritecode" value="'.$unqid.'" />'.
                       '<input type="hidden" name="cid" id="lecturecid" value="'.$cid.'" />'. 
                       'About'.
                       '<p><textarea type="text" name="Description" id="lectureDescription" onChange="check();"></textarea></p>'.
                       '<p> <span id = "aboutAdd">To download the file, enter a Name and Description </span> <img id="RunLoadingRun" width="32" height ="32" src = "/www/images/YTLoad.gif" hidden></p>'.
                       '<p id = "aboutFiles">Allowed file formats: WMV, FLV, AVI, MPEG4, 3GPP, MOV, MPEGPS, WebM files</p>'.
                        '<p id = "aboutTime">Upload HD-video up to 15 minutes</p>'.
                       '
                                       <span>Choose a lecture:</span>
                                       <input name="file" type="file" id="fileAdd" disabled/>'.
                       '<input name="token" type="hidden" value="'. $tokenValue .'"/>'.
                       '<p><input name = "goForest" value="Upload Lecture" type="submit" 
                           id="SendData" style="margin-top: 18px;"
                           class="btn btn-inverse" disabled /></p>'.
                       '</form>';
                    }
                }
                  $this->view->script = 1;
                } catch(Zend_Gdata_App_Exception $e){
                    if ($session->locale) {
                        if($session->locale == 'ru_RU'){
                            $this->view->result = 'Не удалось подключиться к youtube';
                        } else {
                            $this->view->result = 'Not connect to youtube';
                        }
                    }
                    $this->view->script = 3;
                //$this->view->gDataEx = $e->getMessage();
            }
            $this->view->site = $this->getFrontController()->getParam('bootstrap')->getOption('urlsite');
            $this->view->form = $form;
            
            //$email = "asd@asdad.ru";            
            //$lecture->sendNoticeEmail($email);
            
        }
    }

     /**
     * Редактирование лекции
     */
    public function editAction() 
    {
        $id = (int) $this->getRequest()->getParam('lid');
        $cid = (int) $this->getRequest()->getParam('id');
        $session = new Zend_Session_Namespace('lectureBox.l10n');
        if ($session->locale) {
            if($session->locale == 'ru_RU'){
                 $this->view->title = 'Редактирование лекции';
                    $this->view->headTitle($this->view->title, 'PREPEND');
                    $this->view->headMeta()->appendName('description',
                    'Редактировать лекцию. Страница редактировать лекции.');
            }else{
                 $this->view->title = 'Editing lecture';
                 $this->view->headTitle($this->view->title, 'PREPEND');
                 $this->view->headMeta()->appendName('description',
                        'Editing lecture page.');
            }
        }
        
        // Проверка прав доступа
        $acl = Zend_Registry::get('acl');
        $auth = Zend_Auth::getInstance();
        $identity = $auth->getIdentity();
        $role = Bootstrap::getRole($identity->role);
        
        $course = new Model_Lecture($id);
        $_row = $course->getLectureById($id);
        foreach ($_row as $item){
            $this->iddd = $item['lecture_id'];
            $this->iudd = $item['user_id'];
        }

        if(!isset($this->iddd)){
            $this->getHelper('Redirector')->gotoSimpleAndExit('nfound','Error', false,array(null));
        }
        if($this->user_id != $this->iudd){
            if($role != 'admin'){
                $this->getHelper('Redirector')->gotoSimpleAndExit('access','Error', false,array(null)); 
            }
        }
        
        if(!$acl->isAllowed($role, 'mvc:lectures', 'edit'))
            return $this->_forward('login');
       
        $form = new Form_EditLec();
        
        $lid = $this->getParam('lid');

        if ($this->getRequest()->isPost()
                && $form->isValid($this->getRequest()->getPost()))
        {
            $data = array (                    
                 'title' => $form->getValue('title'),
                 'text' => $form->getValue('text')
             );

             // Сохраняем изменения в БД
             Zend_Db_Table::getDefaultAdapter()->update(
                     TABLE_PREF . 'lectures', $data, 'lecture_id=' . $lid);
            
            if ($session->locale) {
                if($session->locale == 'ru_RU'){
                    $this->_helper->flashMessenger->addMessage(
                    '<li class="text-success">Сохранено!</li>');
                } else {
                    $this->_helper->flashMessenger->addMessage(
                    '<li class="text-success">Saved!</li>');
                }
            }
            $this->_redirect($_SERVER['REQUEST_URI']);
        }
        else
        {
             // Вставляем в форму актуальные значения полей
            $lecture = new Model_Lecture();            
            $_row = $lecture->getLectureById($lid);
            foreach ($_row as $item){
                $form->setDefault('title', $item['title']);
                $form->setDefault('text', $item['text']);
            } 
        }
        $this->view->cid = $cid;
        $this->view->form = $form;
    }    
    
    public function delAction() 
    {
        $lid = (int) $this->getRequest()->getParam('id');
        $cid = (int) $this->getRequest()->getParam('cid');
        $session = new Zend_Session_Namespace('lectureBox.l10n');
        
        $auth = Zend_Auth::getInstance();
        $identity = $auth->getIdentity();
        $role = Bootstrap::getRole($identity->role);
        
       
        ///
        $lecture = new Model_Lecture(); 
         $_row = $lecture->getLectureById($lid);
        foreach ($_row as $item){
            $this->iddd = $item['lecture_id'];
            $this->iudd = $item['user_id'];
        }
///
        if(!isset($this->iddd)){
            $this->getHelper('Redirector')->gotoSimpleAndExit('nfound','Error', false,array(null));
        }
        if($this->user_id != $this->iudd){
            if($role != 'admin'){
                $this->getHelper('Redirector')->gotoSimpleAndExit('access','Error', false,array(null)); 
            }
        }
        $lecture->delLecture($lid);
        
        if ($session->locale) {
            if($session->locale == 'ru_RU'){
                $this->_helper->flashMessenger->addMessage(
                '<li class="text-success">Лекция удалена!</li>');
            } else {
                $this->_helper->flashMessenger->addMessage(
                '<li class="text-success">Lecture removed!</li>');
            }
        }
        $this->_redirect('admin/lectures');
    }
    
    public function ajaxAction(){
      $this->_helper->layout->disableLayout();
      $this->_helper->viewRenderer->setNoRender();

       //$title = $this->getParam('title');
       //$decs = $this->getParam('decs');
       //$code = $this->getParam('code');
       //$cid = $this->getParam('cid');

           if($this->getRequest()->isPost()){
               $resource = $this->getRequest()->getPost();
               $work = new Model_Lecture();
               $work->youtube_id = 0;
               $work->course_id = $resource['cid'];
               $work->title = $resource['tit'];
               $work->text = $resource['dec'];
               $work->rank_value = 0;
               $work->rank_count = 0;
               $work->writecode = $resource['code'];
               $work->user_id = 0;
               $work->save();
        }
    }

     public function ajaxtlAction(){
       $this->_helper->layout->disableLayout();
       $this->_helper->viewRenderer->setNoRender();

        //$title = $this->getParam('title');
       // $decs = $this->getParam('decs');
        //$code = $this->getParam('code');
        //$cid = $this->getParam('cid');
        
            if($this->getRequest()->isPost()){
                $resource = $this->getRequest()->getPost();
                    
                $subject = new Model_Course();
                $_row = $subject->getCoursesById($resource['cid']);

                foreach ($_row as $item){
                     $this->cname = $item['name'];
                }            

                $timeline = new Model_Timeline();            
                $this->isVisited = count($timeline->checkTimeline($resource['uid'],
                        $resource['vid']));   
                if(!$this->isVisited){
                    $timeline->setTimeline($resource['uid'], $resource['vid'], $resource['lt'], $this->cname);   
                }
                else{ 
                    $timeline->updateTimelineDate($resource['uid'], $resource['vid']);
                }
            }
        
        }
    
    public function ajaxraitAction(){
       $this->_helper->layout->disableLayout();
       $this->_helper->viewRenderer->setNoRender();
                 
       $userId = $this->getParam('uid');
       $video_id = $this->getParam('lid');
       $val = $this->getParam('ra');

       if($userId && $video_id){
           //echo $video_id;
           //echo $userId;
           
           $work = new Model_Rank();
           $work->lecture_id = $video_id;
           $work->user_id = $userId;
           $work->save();
           
           $Lecture = new Model_Lecture($video_id);
           $Lecture->rank_value += $val;
           $Lecture->rank_count += 1;
           $Lecture->save();
           
           $subject = new Model_Course();
           $_row = $subject->getCoursesById($Lecture->course_id);

                foreach ($_row as $item){
                     $this->cname = $item['name'];
                }            

                $timeline = new Model_Timeline();            
                $this->isVisited = count($timeline->checkTimeline($userId,$video_id));   
                if(!$this->isVisited){
                    $timeline->setTimeline($userId, $video_id, $Lecture->title, $this->cname);
                    $timeline->setTimelineRank($val, $this->user_id, $video_id);
                }
                else{ 
                    $timeline->updateTimelineDate($userId, $video_id);
                    $timeline->setTimelineRank($val, $this->user_id, $video_id);
                }
            }
           
           $jsonData = 'оценок нет';
           if($Lecture->rank_count){
               $jsonData = round($Lecture->rank_value/$Lecture->rank_count,1);
           }
           echo (string)$jsonData;
           //echo '1';
       }
       
    public function ajaxvideoAction(){
       $this->_helper->layout->disableLayout();
       $this->_helper->viewRenderer->setNoRender();
                 
       $userId = $this->getParam('uid');
       $video_id = $this->getParam('lid');
       
       $video = new Model_Lecture($video_id);
       $VideoState = 0;
       if($video->user_id == $userId){
          // $VideoState['isUser'] = '1';
       }
       try{
            $yt = new Zend_Gdata_YouTube();
            try{
                $state = $yt->getVideoEntry($video->youtube_id)->getVideoState();
                    if (empty($state)){
                        $VideoState = 1;
                        
            //Всё гуд 1
                    } else {
                        if(is_string($state->encode())){
                            if($state->getText() == 'Duplicate video'){
                          $VideoState = 3;
                            $video->writecode = 'dub';
                            $video->course_id = 0;
                            $video->user_id = 0;
                            $video->save();
                            $ranks = new Model_Rank($video->lecture_id);
                            foreach ($ranks as $rank){
                                $rank->delete();
                            }
                            $timeTables = new Model_Timeline();
                            $timeTables->getTimelineByLecture($video->lecture_id);
                            foreach ($timeTables as $timeTable){
                                $timeTable->delete();
                            }
                         //уже было и будет удалено 3
                    }
                    else{
                        $VideoState = 2;
                       // Модерация 2
                    }
                }else{
                     $VideoState = 2;
                    // Модерация 2
                }
        }
        }catch(Zend_Gdata_App_Exception $e){
            if(substr($e->getMessage(),36) == 'Video not found' || substr($e->getMessage(),36) == 'Invalid id'){
                $VideoState = 4;
                $video->writecode = 'deleted';
                $video->course_id = 0;
                $video->user_id = 0;
                $video->save();
                $ranks = new Model_Rank($video->lecture_id);
                        foreach ($ranks as $rank){
                           $rank->delete();
                        }
                        $timeTables = new Model_Timeline();
                        $timeTables->getTimelineByLecture($video->lecture_id);
                        foreach ($timeTables as $timeTable){
                            $timeTable->delete();
                        }
                // Видео скорее всего удалено 4
                } elseif (substr($e->getMessage(),36) == 'Private video' ){
                    $VideoState = 3;
                    $video->writecode = 'dub';
                    $video->course_id = 0;
                    $video->user_id = 0;
                    $video->save();
                    $ranks = new Model_Rank($video->lecture_id);
                        foreach ($ranks as $rank){
                           $rank->delete();
                        }
                        $timeTables = new Model_Timeline();
                        $timeTables->getTimelineByLecture($video->lecture_id);
                        foreach ($timeTables as $timeTable){
                            $timeTable->delete();
                        }
                } else {
                     $VideoState = 5;
                    //что-то другое 5
                }

        }
        } catch (Zend_Gdata_App_Exception $e){
            $VideoState = 5;
            //что-то другое 5
        }
        //echo $VideoState['Code'];
       //$this->_hepler->json($VideoState);
       //print_r($VideoState);
        echo $VideoState;
    }

    /**
     * Одна лекция на странице
     * /lectures/single/id/123
     */
    public function singleAction()
    {
        // Если нужно вывести только 1 лекцию
        $lecture_id = (int) $this->getRequest()->getParam('id', 0);
        if($lecture_id)
        {
            $lecture = new Model_Lecture();
            $this->view->pages = $lecture->getPaginatorPageById($lecture_id);

            foreach ($this->view->pages as $item){
                 $this->isit = $item['lecture_id'];
            }
            if(!isset($this->isit)){
                $this->getHelper('Redirector')->gotoSimpleAndExit('nfound','Error', false,array(null));
            }
            
            $YTstate = 0;
            if(count($this->view->pages))
            {
                foreach($this->view->pages as $item){
                    $this->ltitle = $item['title'];
                    $this->cid = $item['course_id'];
                    $this->creatorId = $item['user_id'];
                    break;
                }
                //$authenticationURL = 'https://www.google.com/accounts/ClientLogin'; 
                try{
//                    $httpClient = Zend_Gdata_ClientLogin::getHttpClient(
//                            $this->getFrontController()->getParam('bootstrap')->getOption('yusername'),                                                                                                                                                                               
//                            $this->getFrontController()->getParam('bootstrap')->getOption('ypassword'),                                                                          
//                            $this->getFrontController()->getParam('bootstrap')->getOption('yservice'),                                                                                                                          
//                            null,                                                                                                                                 
//                            $this->getFrontController()->getParam('bootstrap')->getOption('yname'),                                                                              
//                            null,                                                                                                                             
//                            null,                                                                                                                           
//                            $authenticationURL);
//
//                    $developerKey = $this->getFrontController()->getParam('bootstrap')->getOption('ycode');                                                                                              
//                    $httpClient->setHeaders('X-GData-Key', "key=$developerKey"); //ключ разработчика

                    //$yt = new Zend_Gdata_YouTube($httpClient);
                    $yt = new Zend_Gdata_YouTube();
                    try{
                        $state = $yt->getVideoEntry($item['youtube_id'])->getVideoState();
                            if (empty($state)){
                                $this->view->vistate = 1;
                                $YTstate = 1;
                    //Всё гуд 1
                            } else {
                                if(is_string($state->encode())){
                                    if($state->getText() == 'Duplicate video'){
                                 $this->view->vistate = 3;
                                 $videos = new Model_Lecture($lecture_id);
                                 $videos->writecode = 'dub';
                                 $videos->course_id = 0;
                                 $videos->user_id = 0;
                                 $videos->save();
                                 $ranks = new Model_Rank();
                                $ran = $ranks->getRankByLectureId($lecture_id);
                                foreach ($ran as $rank){
                                   $rank->delete();
                                }
                                $timeTables = new Model_Timeline();
                                $timeL = $timeTables->getTimelineByLecture($lecture_id);
                                foreach ($timeL as $timeTable){
                                        $timeTable->delete();
                                }
                                 //уже было и будет удалено 3
                            }
                            else{
                               $this->view->vistate = 2;;
                               // Модерация 2
                            }
                        }else{
                            $this->view->vistate = 2;
                            // Модерация 2
                        }
                }
                }catch(Zend_Gdata_App_Exception $e){
                    if(substr($e->getMessage(),36) == 'Video not found' || substr($e->getMessage(),36) == 'Invalid id'){
                        $this->view->vistate = 4;
                        $videos = new Model_Lecture($lecture_id);
                        $videos->writecode = 'deleted';
                        $videos->course_id = 0;
                        $videos->user_id = 0;
                        $videos->save();
                        $ranks = new Model_Rank();
                        $ran = $ranks->getRankByLectureId($lecture_id);
                        foreach ($ran as $rank){
                           $rank->delete();
                        }
                        $timeTables = new Model_Timeline();
                        $timeL = $timeTables->getTimelineByLecture($lecture_id);
                        foreach ($timeL as $timeTable){
                                $timeTable->delete();
                        }
                        } elseif (substr($e->getMessage(),36) == 'Private video' ){
                            $this->view->vistate = 3;
                            $videos = new Model_Lecture($lecture_id);
                            $videos->writecode = 'dub';
                            $videos->course_id = 0;
                            $videos->user_id = 0;
                            $videos->save();
                            $ranks = new Model_Rank();
                            $ran = $ranks->getRankByLectureId($lecture_id);
                            foreach ($ran as $rank){
                               $rank->delete();
                            }
                            $timeTables = new Model_Timeline();
                            $timeL = $timeTables->getTimelineByLecture($lecture_id);
                            foreach ($timeL as $timeTable){
                                    $timeTable->delete();
                            }
                        } else {
                            $this->view->vistate = 5;
                            //что-то другое 5
                        }

                }
                } catch (Zend_Gdata_App_Exception $e){
                    $this->view->vistate = 5;
                    //что-то другое 5
                }
                
                
                $title = htmlspecialchars($item['title']);
                $session = new Zend_Session_Namespace('lectureBox.l10n');
                if ($session->locale) {
                    if($session->locale == 'ru_RU'){
                        $this->view->headTitle($title, 'PREPEND');
                        $this->view->headTitle("Лекция номер $lecture_id ");
                        $this->view->headMeta()->appendName('description',
                            'Смотреть лекции' . $title);
                    } else {
                                                $this->view->headTitle($title, 'PREPEND');
                        $this->view->headTitle("Lecture number $lecture_id ");
                        $this->view->headMeta()->appendName('description',
                            'Watch Lectures' . $title);
                        
                    }
                }
                
            }

//            if($YTstate == 1){
//                $subject = new Model_Course();
//                $_row = $subject->getCoursesById($this->cid);
//
//                foreach ($_row as $item){
//                     $this->cname = $item['name'];
//                }            
//
//                $timeline = new Model_Timeline();            
//                $this->isVisited = count($timeline->checkTimeline($this->user_id,
//                        $lecture_id));   
//                if(!$this->isVisited){
//                    $timeline->setTimeline($this->user_id, $lecture_id,
//                            $this->ltitle, $this->cname);   
//                }
//                else $timeline->updateTimelineDate($this->user_id, $lecture_id);   
//            }
        }
        
        $rank = new Model_Rank();
        //$rank->ifUserRankVideo($lecture_id, $this->user_id);
        $this->view->isRanked = count($rank->ifUserRankVideo($lecture_id, $this->user_id));
        $this->view->lec_id = $lecture_id;
        $this->view->user_id = $this->user_id;
        $this->view->site = $this->getFrontController()->getParam('bootstrap')->getOption('urlsite');
    }

    /**
     * Вывод по тэгам
     * Пример:
     * /lectures/tag/page/1/label/1
     *  - страница = 1, тэг id = 1
     */
//    public function tagAction()
//    {
//        $page = (int) $this->getRequest()->getParam('page', 1);
//        $tag = (int) $this->getRequest()->getParam('label', 0);
//
//        $work = new Model_Lecture();
//        $this->view->pages = $work->getPaginatorRows($page, 5, $tag);
//        if(count($this->view->pages))
//        {
//            foreach($this->view->pages as $item)
//                break;
//            $title = htmlspecialchars($item['labels'][0]['label']);
//            $this->view->title = 'Тег: ' . $title ;
//            $this->view->headTitle($title, 'PREPEND');
//
//            $this->view->headMeta()->appendName('description',
//                'Смотреть лекции. Тег ' . $title);
//        }
//        $this->view->user_id = $this->user_id;
//    }
    
    /**
     * Вывод по разделам
     * Пример:
     * /lectures/cat/page/1/id/1
     *  - страница = 1, тэг id = 1
     */
    public function subjectAction()
    {
        $session = new Zend_Session_Namespace('lectureBox.l10n');
        $id = (int) $this->getRequest()->getParam('id', 0);
        $subject = new Model_Subject();
        $_row = $subject->getSubjectsById($id);
        
 		foreach ($_row as $item){
           if ($session->locale == 'ru_RU') 
				$this->view->title = 'Курсы раздела ';
	       else 
				$this->view->title = 'Sections of courses ';
			 
			$this->view->cname = $item['name'];	
        } 

        $this->view->headTitle($this->view->title, 'PREPEND');
        if ($session->locale) {
                    if($session->locale == 'ru_RU'){
                        $this->view->headMeta()->appendName('description',
                                'Курсы предмета');
                    }else{
                        $this->view->headMeta()->appendName('description',
                                'Sections of courses');
                    }
        }
        $this->view->headTitle($this->view->title, 'PREPEND');        
        $course = new Model_Course();            
        $this->view->courses = $course->getCoursesByIdSub($id);
        $this->view->sid = $id;
        $this->view->user_id = $this->user_id;
    }
 
     /**
     * Вывод по разделам
     * Пример:
     * /lectures/cat/page/1/id/1
     *  - страница = 1, тэг id = 1
     */
    public function timelineAction()
    {
        //$id = (int) $this->getRequest()->getParam('uid', 0);
        //$subject = new Model_Subject();
        //$_row = $subject->getSubjectsById($id);
        
        //foreach ($_row as $item){
        $session = new Zend_Session_Namespace('lectureBox.l10n');
        if ($session->locale) {
                    if($session->locale == 'ru_RU'){
                    $this->view->title = 'История просмотренных лекций пользователя ' .
                            $this->view->username;
                    } else {
                        $this->view->title = 'Viewed lectures History user ' .
                            $this->view->username;
                    }
        }
        //}       

        $this->view->headTitle($this->view->title, 'PREPEND');
        if ($session->locale) {
                    if($session->locale == 'ru_RU'){
        $this->view->headMeta()->appendName('description',
                'История просмотренных лекций пользователя');
                    }else{
                        $this->view->headMeta()->appendName('description',
                'Viewed lectures History user');
                    }
        }
        $this->view->headTitle($this->view->title, 'PREPEND'); 
        
        $timeline = new Model_Timeline();
        $this->view->timelines = $timeline->getTimelineByUser($this->user_id);
    }
    
}